<?php

namespace app\common\model\xilujob;

use think\Cache;
use think\db\Query;
use think\Model;

/**
 * 地区数据模型
 */
class Area extends Model
{
    protected $name = 'xilujob_area';
    /**
     * 根据经纬度获取当前地区信息
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area 城市信息
     */
    public static function getAreaFromLngLat($lng, $lat, $level = 3)
    {
        $namearr = [1 => 'geo:province', 2 => 'geo:city', 3 => 'geo:district'];
        $rangearr = [1 => 15000, 2 => 1000, 3 => 200];
        $geoname = isset($namearr[$level]) ? $namearr[$level] : $namearr[3];
        $georange = isset($rangearr[$level]) ? $rangearr[$level] : $rangearr[3];
        // 读取范围内的ID
        $redis = Cache::store('redis')->handler();
        $georadiuslist = [];
        if (method_exists($redis, 'georadius')) {
            $georadiuslist = $redis->georadius($geoname, $lng, $lat, $georange, 'km', ['WITHDIST', 'COUNT' => 5, 'ASC']);
        }

        if ($georadiuslist) {
            list($id, $distance) = $georadiuslist[0];
        }
        $id = isset($id) && $id ? $id : 3;
        return self::get($id);
    }

    /**
     * 根据经纬度获取省份
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area
     */
    public static function getProvinceFromLngLat($lng, $lat)
    {
        $provincedata = null;
        $citydata = self::getCityFromLngLat($lng, $lat);
        if ($citydata) {
            $provincedata = self::get($citydata['pid']);
        }
        return $provincedata;
    }

    /**
     * 根据经纬度获取城市
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area
     */
    public static function getCityFromLngLat($lng, $lat)
    {
        $citydata = null;
        $districtdata = self::getDistrictFromLngLat($lng, $lat);
        if ($districtdata) {
            $citydata = self::get($districtdata['pid']);
        }
        return $citydata;
    }

    /**
     * 根据经纬度获取地区
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area
     */
    public static function getDistrictFromLngLat($lng, $lat)
    {
        $districtdata = self::getAreaFromLngLat($lng, $lat, 3);
        return $districtdata;
    }

    public static function getDistrictsWith($cityId, $useCache=true) {
        $cacheKey = 'districts_with_'.$cityId;
        $data = $useCache ? Cache::get($cacheKey) : null;
        if(!$data) {
            $data = self::where('level', 3)->where('pid', $cityId)
                ->with(['children' => function (Query $query) {
                    $query->field('id,pid,name');
                }])
                ->order('weigh desc')
                ->field('id,name')
                ->select();
            Cache::set($cacheKey, $data, 3600);
        }
        return $data;
    }

    /**
     * 省市区三级树状结构
     * @param bool $useCache
     * @return bool|false|mixed|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAreaTree() {
        $data = self::where('level', 1)
            ->with(['children' => function (Query $query) {
                $query->with(['children' => function (Query $query) {
                    $query->field('id,pid,name')->where('level',3);
                }])->where('level',2)->field('id,pid,name');
            }])
            ->order('weigh asc')
            ->field('id,name')
            ->select();
        return $data;
    }

    public function children() {
        return $this->hasMany('Area', 'pid', 'id');
    }

    public static function get_cities(){
        $cacheKey = 'first_city_sort';
        $data = Cache::get($cacheKey);
        if(!$data) {
            $data = self::field('first')
                ->with(['cities'=>function($query){
                    $query->field(['id','name','first']);
                }])
                ->group('first')
                ->order('first','asc')
                ->where('level',2)
                ->select();
            Cache::set($cacheKey, $data, 3600);
        }
        return $data;
    }


    public function cities(){
        return $this->hasMany('Area', 'first', 'first');
    }


    /**
     * 根据name获取id
     * @param $name
     * @param int $level
     */
    public static function getIdByName($name,$level=1,$pid=0){
        $id = self::where('name','like',$name.'%')->where('level',$level)->value('id');
        if(!$id){
            $area = self::create([
                'name'      =>  $name,
                'shortname' =>  $name,
                'status'    => '1',
                'pid'       =>  $pid,
                'level'     => $level
            ]);
            $id = $area->id;
        }
        return $id;
    }
}
